package network;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

public class FileConnection {
    private static RandomAccessFile logFile;
    private static String currentLogFileName;
    private static RandomAccessFile errorFile;
    private static RandomAccessFile authFile;
    private static final String encoding = "UTF-8";
    private static final String dateFormat = "yyyy-MM-dd HH-mm";
    private static SimpleDateFormat sdfDate = new SimpleDateFormat(dateFormat);

    public static void loadFile() {
        try {
            //String currentFileName =
            SimpleDateFormat sdfDate = new SimpleDateFormat(dateFormat);
            Date now = new Date();
            createLogFile(sdfDate.format(now));
            logFile.skipBytes((int) logFile.length());
            errorFile = new RandomAccessFile(Configuration.getErrorFileName(), "rw");
            errorFile.skipBytes((int) errorFile.length());
            authFile = new RandomAccessFile(Configuration.getAuthenticationFileName(), "r");
        } catch (FileNotFoundException e) {
            System.err.println("Could not open logFile");
        } catch (IOException e) {
            System.err.println("Skipp failed");
        }
    }

    public static void createLogFile(String fileName) throws FileNotFoundException {
        logFile = new RandomAccessFile(Configuration.getHistoryFilePath() + "\\" + fileName + ".log", "rw");
        currentLogFileName = fileName;
    }

    public static HashMap<String, String> loadAuthData() throws IOException {
        HashMap<String, String> authData = new HashMap<>();
        String line;
        while ((line = authFile.readLine()) != null) {
            String[] items = line.split(";");
            if (items.length != 2) {
                throw new IOException("Incorrect file format. Need: <login>;<pwd>");
            }
            authData.put(items[0], items[1]);
        }
        return authData;
    }

    public static void log_write(String message) throws IOException {
        try {
            synchronized (logFile) {
                Date fileDate = new SimpleDateFormat(dateFormat, Locale.ENGLISH).parse(currentLogFileName);
                Date currentDate = new Date();
                if ((currentDate.getTime() - fileDate.getTime()) / (60*1000) >= Configuration.getHistoryDelay()) {
                    logFile.close();
                    File file = new File(Configuration.getHistoryFilePath() + "\\" + currentLogFileName + ".log");
                    file.delete();
                    createLogFile(sdfDate.format(currentDate));
                }
                logFile.write((message + "\r\n").getBytes(encoding));
            }
        } catch (ParseException | IOException e) {
            System.err.println("Could not write into log_file: " + message);
        }
    }

    public static void error_write(String message) {
        try {
            synchronized (errorFile) {
                errorFile.write((new Date() + "> " + message + "\r\n").getBytes(encoding));
            }
        } catch (IOException e) {
            System.err.println("Could not write into error_file " + message);
        }
    }

    public static String getHistory() throws IOException {
        synchronized (logFile) {
            int mark = (int) logFile.length();
            logFile.seek(0);
            byte[] history = new byte[mark];
            logFile.readFully(history, 0, mark);
            return (new String(history, encoding));
        }
    }
}
